<template>
  <div class="parameter-selector">
    <!-- 筛选区域 -->
    <div class="filter-section">
      <div class="filter-row">
        <div class="filter-item">
          <label class="filter-label">机组编号</label>
          <select v-model="selectedUnit" class="filter-select">
            <option value="">请选择机组编号</option>
            <option
              v-for="unit in props.unitCodeList"
              :key="unit"
              :value="unit"
            >
              {{ unit }}
            </option>
          </select>
        </div>
        <div class="filter-item">
          <label class="filter-label">开始时间</label>
          <DateTimeSelector
            v-model="startDateTime"
            class="filter-datetime-input"
            placeholder="选择开始时间"
          />
        </div>
        <div class="filter-item">
          <label class="filter-label">结束时间</label>
          <DateTimeSelector
            v-model="endDateTime"
            input-class="filter-datetime-input"
            placeholder="选择结束时间"
          />
        </div>
        <!-- <div class="filter-item filter-item-button">
          <button
            class="tech-btn confirm-filter-btn"
            @click="handleFilterConfirm"
          >
            确认
          </button>
        </div> -->
      </div>
    </div>

    <!-- Tab页 -->
    <div class="selector-card parameter-card">
      <!-- Tab头部已隐藏，只显示参数Tab -->
      <!-- <div class="tab-header">
        <button
          v-for="tab in tabs"
          :key="tab.key"
          :class="['tab-button', { active: activeTab === tab.key }]"
          @click="activeTab = tab.key"
        >
          {{ tab.label }}
        </button>
      </div> -->

      <!-- 参数Tab内容（始终显示，因为Tab头部已隐藏） -->
      <div class="tab-content">
        <div class="card-header">
          <h2 class="card-title">参数选择</h2>
          <div class="search-box flex gap-2">
            <input
              type="text"
              v-model="searchQuery"
              placeholder="搜索参数..."
              class="tech-input"
            />
            <button class="tech-btn clear-button" @click="clearSelectedParams">
              <svg
                class="icon"
                viewBox="0 0 1024 1024"
                width="16"
                height="16"
                fill="currentColor"
                xmlns="http://www.w3.org/2000/svg"
              >
                <circle
                  cx="512"
                  cy="512"
                  r="448"
                  fill="none"
                  stroke="currentColor"
                  stroke-width="64"
                />
                <rect
                  x="192"
                  y="480"
                  width="640"
                  height="64"
                  rx="8"
                  fill="currentColor"
                />
              </svg>
            </button>
          </div>
        </div>
        <div class="card-content" style="position: relative">
          <!-- loading遮罩层，只在card-content区域显示 -->
          <div v-if="isLoading" class="card-loading-overlay">
            <div class="spinner"></div>
          </div>
          <div class="parameter-group">
            <div class="parameter-list">
              <div
                v-for="param in allParameters"
                :key="param.id"
                class="parameter-item-container"
              >
                <div
                  class="parameter-item"
                  :class="{
                    'has-children': param.children && param.children.length > 0,
                  }"
                >
                  <div class="parameter-item-content">
                    <label class="tech-checkbox">
                      <input
                        type="checkbox"
                        :value="param.name"
                        :checked="selectedParams.includes(param.name)"
                        @change="handleParamChange(param.name, $event)"
                      />
                      <span class="checkbox-custom"></span>
                      <span class="checkbox-label parameter-list">{{
                        param.name
                      }}</span>
                    </label>
                    <button
                      v-if="param.children && param.children.length > 0"
                      class="expand-btn"
                      @click="toggleExpand(param.name)"
                    >
                      <svg
                        class="h-3 w-3"
                        :class="{
                          'rotate-180': expandedParams.includes(param.name),
                        }"
                        viewBox="0 0 24 24"
                        fill="none"
                        stroke="currentColor"
                        stroke-width="2"
                      >
                        <path d="M19 9l-7 7-7-7" />
                      </svg>
                    </button>
                  </div>
                </div>

                <div
                  v-if="
                    param.children &&
                    param.children.length > 0 &&
                    expandedParams.includes(param.name)
                  "
                  class="parameter-children"
                >
                  <div
                    v-for="child in param.children"
                    :key="child.name"
                    class="parameter-child-item"
                  >
                    <label class="tech-checkbox">
                      <input
                        type="checkbox"
                        :value="child.name"
                        :checked="selectedParams.includes(child.name)"
                        @change="handleParamChange(child.name, $event)"
                      />
                      <span class="checkbox-custom"></span>
                      <span class="checkbox-label parameter-list">{{
                        child.name
                      }}</span>
                    </label>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 设备和算法Tab内容已隐藏 -->
      <!-- <div v-if="activeTab === 'device'" class="tab-content">
        <div class="card-content">
          <div class="empty-tab-content">
            <p>设备内容暂未实现</p>
          </div>
        </div>
      </div>

      <div v-if="activeTab === 'algorithm'" class="tab-content">
        <div class="card-content">
          <div class="empty-tab-content">
            <p>算法内容暂未实现</p>
          </div>
        </div>
      </div> -->
    </div>

    <!-- <div class="selector-card task-card">
      <div class="card-header">
        <h2 class="card-title">回放任务</h2>
      </div>
      <div class="card-content">
        <div class="task-controls">
          <div class="select-wrapper">
            <div class="select-container">
              <select
                class="tech-select"
                v-model="selectedTask"
                @change="handleTaskChange"
              >
                <option value="" disabled selected>选择回放任务</option>
                <option
                  v-for="task in tasks"
                  :key="task.id"
                  :value="task.id"
                  :title="task.name"
                  class="truncate-option"
                >
                  {{ task.name.length > 20 ? task.name.substring(0, 10) + '...' : task.name }}
                </option>
              </select>
              <div class="select-arrow" v-if="!selectedTask"></div>
              <button
                v-if="selectedTask"
                class="clear-btn"
                @click.stop="clearSelectedTask"
              >
                <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                  <line x1="18" y1="6" x2="6" y2="18"></line>
                  <line x1="6" y1="6" x2="18" y2="18"></line>
                </svg>
              </button>
            </div>
          </div>
          <div class="flex gap-1.5">
              <div class="tooltip-container">
                <button class="tech-btn save-btn" @click="handleSaveParams" :disabled="selectedParams.length === 0">
                  <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                    <path d="M19 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11l5 5v11a2 2 0 0 1-2 2z"></path>
                    <polyline points="17 21 17 13 7 13 7 21"></polyline>
                    <polyline points="7 3 7 8 15 8"></polyline>
                  </svg>
                </button>
                <span class="tooltip-text">保存</span>
              </div>
              <div class="tooltip-container">
                  <button class="tech-btn save-btn" @click="handleSaveTask" :disabled="!selectedTask">
                  <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                    <path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"></path>
                    <path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"></path>
                  </svg>
                </button>
                <span class="tooltip-text">编辑</span>
              </div>
              <div class="tooltip-container">
                  <button class="tech-btn-warn save-btn delete-btn" @click="handleDeleteTask" :disabled="!selectedTask">
                  <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                    <polyline points="3 6 5 6 21 6"></polyline>
                    <path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"></path>
                  </svg>
                </button>
                <span class="tooltip-text">删除</span>
              </div>
          </div>
        </div>
      </div>
    </div> -->
  </div>
  <div v-if="importFileWarn" class="warn-overlay">
    <div class="modal-main">
      <div class="modal-header">
        <h3 class="warn-title">提示</h3>
        <button class="warn-close" @click="closeWarn">
          <svg
            class="h-4 w-4"
            viewBox="0 0 24 24"
            fill="none"
            stroke="currentColor"
            stroke-width="2"
          >
            <path d="M18 6L6 18M6 6l12 12" />
          </svg>
        </button>
      </div>
      <div class="guide-content">
        <p>请选择文件</p>
        <button class="import-btn tech-btn" @click="closeWarn">确定</button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import {
  ref,
  onMounted,
  watch,
  computed,
  onBeforeUnmount,
  nextTick,
} from "vue";
import type { Parameter, Task } from "../../types";
import { debounce } from "lodash-es";
import API from "@/views/playbackTask/playbackTask.api.ts";
import DateTimeSelector from "@/components/BaseComponents/DateTimeSelector.vue";
// 扩展Parameter类型以支持children字段
interface ParameterWithChildren extends Parameter {
  children?: ParameterWithChildren[];
}

const props = defineProps({
  parameters: {
    type: Array as () => Parameter[],
  },
  tasks: {
    type: Array as () => Task[],
  },
  isLoading: {
    type: Boolean,
    default: false,
  },
  unitCodeList: {
    type: Array as () => string[],
    default: () => ["1ZXC1", "1ZXC2", "1ZXC3"],
  },
});
const tasks = ref([]);
const emit = defineEmits<{
  (e: "update:selectedParameters", value: string[]): void;
  (
    e: "update:selectedParametersInfo",
    value: Array<{ id: string; name: string; type?: string }>
  ): void;
  (e: "update:selectedTasks", value: string[]): void;
  (e: "update:viewSettings", value: any): void;
  (e: "handleChangeTask"): void;
  (e: "refresh:parameter"): void;
  (e: "refresh:dataViewer"): void;
}>();

// 所有参数的选择数组
const selectedParams = ref<string[]>([]);
const selectedTask = ref<string>("");

// 展开的参数ID数组
const expandedParams = ref<string[]>([]);

// Tab相关
const activeTab = ref<string>("parameter");
const tabs = [
  { key: "parameter", label: "参数" },
  { key: "device", label: "设备" },
  { key: "algorithm", label: "算法" },
];

// 筛选区域相关
const selectedUnit = ref<string>("");
const startDateTime = ref<string>("");
const endDateTime = ref<string>("");

// 监听机组编号变化，自动触发参数查询
watch(
  selectedUnit,
  (newUnitCode, oldUnitCode) => {
    // 只有当选择了新的机组编号（不为空）且与之前不同时才触发查询
    // 避免初始化时触发（oldUnitCode 为 undefined 时可能是初始化）
    if (
      newUnitCode &&
      newUnitCode !== oldUnitCode &&
      oldUnitCode !== undefined
    ) {
      console.log("机组编号变化，触发参数查询:", newUnitCode);
      // 触发事件通知父组件查询参数
      emit("refresh:parameter");
      // 同时更新localStorage
      localStorage.setItem("unitCode", newUnitCode);
    }
  },
  { immediate: false }
);
// 监听开始时间和结束时间变化
watch(
  [startDateTime, endDateTime],
  ([newStart, newEnd], [oldStart, oldEnd]) => {
    if (newStart && newEnd && selectedUnit.value) {
      // 判断开始时间小于结束时间，否则不刷新
      if (newStart >= newEnd) {
        emit("handleParameterError", "warning", "开始时间必须小于结束时间");
        return;
      }
      localStorage.setItem("startTime", newStart);
      localStorage.setItem("endTime", newEnd);
      emit("refresh:dataViewer");
    }
  }
);

// 切换参数展开/折叠状态
const toggleExpand = (paramId: string) => {
  // 如果正在加载中，不允许展开/折叠
  if (props.isLoading) {
    return;
  }

  const index = expandedParams.value.indexOf(paramId);
  if (index === -1) {
    expandedParams.value.push(paramId);
  } else {
    expandedParams.value.splice(index, 1);
  }
};

// 所有参数列表
const searchQuery = ref("");

// 过滤后的参数列表（不显示RecTime）
const allParameters = computed(() => {
  const params = (props.parameters || []).filter(
    (param) => param.name !== "RecTime"
  );
  if (!searchQuery.value) return params;

  const searchTerm = searchQuery.value.toLowerCase();

  const filterParams = (paramsList: ParameterWithChildren[]) => {
    return paramsList
      .filter((param) => param.name !== "RecTime")
      .filter((param) => {
        const matchSelf = param.name.toLowerCase().includes(searchTerm);
        const matchChildren = param.children?.some(
          (child) =>
            child.name.toLowerCase().includes(searchTerm) &&
            child.name !== "RecTime"
        );
        return matchSelf || matchChildren;
      })
      .map((param) => ({
        ...param,
        children: param.children
          ? filterParams(
              param.children.filter((child) => child.name !== "RecTime")
            )
          : undefined,
      }));
  };

  return filterParams(params);
});

const importFileWarn = ref(false);
// 监听参数选择变化
watch(
  selectedParams,
  (newValue) => {
    console.log("Selected parameters changed:", newValue);
    const selectedParametersNames: string[] = [];
    const selectedParamsInfo: Array<{
      id: string;
      name: string;
      type?: string;
    }> = [];
    if (props.parameters?.length > 0) {
      props.parameters.forEach((item) => {
        newValue.forEach((name) => {
          if (item.name === name) {
            selectedParamsInfo.push({
              id: item.id,
              name: item.name,
              type: item.type,
            });
            selectedParametersNames.push(item.name);
          }
          // 检查子参数
          if (item.children) {
            item.children.forEach((child: ParameterWithChildren) => {
              if (child.name === name) {
                selectedParamsInfo.push({
                  id: child.id,
                  name: child.name,
                  type: child.type,
                });
                selectedParametersNames.push(child.name);
              }
            });
          }
        });
      });
      emit("update:selectedParameters", selectedParametersNames);
    } else {
      importFileWarn.value = true;
    }
    emit("update:selectedParametersInfo", selectedParamsInfo);
  },
  { deep: true }
);

const closeWarn = () => {
  importFileWarn.value = false;
};

// 监听任务选择变化
watch(
  selectedTask,
  (newValue) => {
    console.log("Selected task changed:", newValue);
    emit("update:selectedTasks", [newValue]);
  },
  { deep: true }
);

// 处理参数变化
const handleParamChange = (paramName: string, event: Event) => {
  // 如果正在加载中，不允许改变选择状态
  if (props.isLoading) {
    return;
  }

  const checkbox = event.target as HTMLInputElement;

  if (checkbox.checked) {
    if (!selectedParams.value.includes(paramName)) {
      selectedParams.value.push(paramName);
    }
  } else {
    selectedParams.value = selectedParams.value.filter(
      (name) => name !== paramName
    );
  }

  console.log("Selected parameters:", selectedParams.value);
};

const handleTaskChange = (event: Event) => {
  const select = event.target as HTMLSelectElement;
  selectedTask.value = select.value;

  console.log("allParameters ======== ", allParameters.value);

  // 清空之前选择的参数
  selectedParams.value = [];
  // 找到选中的任务
  const selectedTaskData = tasks.value.find(
    (task) => task.id.toString() === selectedTask.value
  );
  emit("handleChangeTask");
  // 如果找到任务且有参数数据，则勾选对应参数
  if (selectedTaskData && selectedTaskData.parameters) {
    // 查询viewsettings
    const updatedViewSettings = selectedTaskData.viewSettings;
    // 更新viewsettings
    const updatedViewSettingsObj = JSON.parse(updatedViewSettings);
    // 目前只有leftA，需要补全其他通道leftB、rightA、rightB、RJ
    // 补全其他通道
    const channelKeys = ["leftB", "rightA", "rightB", "RJ"];
    Object.keys(updatedViewSettingsObj).forEach((key) => {
      // 获取参数名称 去掉最后的6个字符
      const paramName = key.split(":")[0];
      channelKeys.forEach((channel) => {
        const newKey = paramName + ":" + channel;
        // 复制updatedViewSettingsObj[key],更新其中的channelId
        const newObj = { ...updatedViewSettingsObj[key], channelId: channel };

        updatedViewSettingsObj[newKey] = newObj;
      });
    });

    emit("update:viewSettings", updatedViewSettingsObj);
    // 确保在搜索状态下也能正确设置参数选中状态
    const paramNames = selectedTaskData.parameters.map(
      (param: any) => param.name
    );
    selectedParams.value = paramNames;

    // 如果有搜索关键词，展开包含选中参数的父节点
    if (searchQuery.value) {
      props.parameters?.forEach((param) => {
        if (param.children) {
          const hasSelectedChild = param.children.some((child) =>
            paramNames.includes(child.name)
          );
          if (hasSelectedChild && !expandedParams.value.includes(param.name)) {
            expandedParams.value.push(param.name);
          }
        }
      });
    }
  }
};

const clearSelectedTask = () => {
  selectedTask.value = "";
  selectedParams.value = [];
  emit("update:selectedTasks", []);
  emit("update:selectedParameters", []);
  emit("update:selectedParametersInfo", []);
};

// 使用防抖处理键盘事件
const handleKeyDown = debounce((event: KeyboardEvent) => {
  // 检查当前焦点是否在输入框上，如果是则不处理上下箭头键事件
  const activeElement = document.activeElement;
  if (
    activeElement &&
    (activeElement.tagName === "INPUT" ||
      activeElement.tagName === "TEXTAREA" ||
      activeElement.contentEditable === "true")
  ) {
    // 如果焦点在输入框上，不处理上下箭头键事件，让输入框正常处理光标移动
    if (event.key === "ArrowUp" || event.key === "ArrowDown") {
      return;
    }
  }

  if (event.key === "ArrowUp" || event.key === "ArrowDown") {
    event.preventDefault();
    const currentIndex = tasks.value.findIndex(
      (task) => task.id.toString() === selectedTask.value
    );
    let newIndex = currentIndex;

    // 处理边界情况
    if (tasks.value.length === 0) return;

    if (currentIndex === -1) {
      // 如果当前没有选中任务，选择第一个任务
      newIndex = 0;
    } else {
      if (event.key === "ArrowUp") {
        newIndex = currentIndex > 0 ? currentIndex - 1 : tasks.value.length - 1;
      } else {
        newIndex = currentIndex < tasks.value.length - 1 ? currentIndex + 1 : 0;
      }
    }

    selectedTask.value = tasks.value[newIndex].id.toString();

    // 手动触发handleTaskChange事件
    const mockEvent = {
      target: {
        value: tasks.value[newIndex].id.toString(),
      },
    };
    handleTaskChange(mockEvent as unknown as Event);
  }
}, 150);

// 全局事件监听器
const setupGlobalKeyboardListener = () => {
  window.addEventListener("keydown", handleKeyDown);
};

const cleanupGlobalKeyboardListener = () => {
  window.removeEventListener("keydown", handleKeyDown);
  handleKeyDown.cancel();
};
function getAllTask() {
  nextTick(() => {
    API.queryAllTask()
      .then((res: any) => {
        if (res && res.code == 200) {
          res.data.forEach((item: any) => {
            item.parameters = JSON.parse(item.parameters);
          });
          tasks.value = res.data;
        } else {
          emit("handleParameterError", "warning", res.msg);
        }
      })
      .catch((error) => {
        emit("handleParameterError", "warning", error.response.data.msg);
      });
  });
}

// 重置已选参数
const resetSelectedParams = () => {
  selectedParams.value = [];
};

// 移除特定参数的选中状态
const removeSelectedParam = (paramName: string) => {
  selectedParams.value = selectedParams.value.filter(
    (name) => name !== paramName
  );
};

// 自动选择参数
const autoSelectParam = (paramName: string) => {
  selectedParams.value = [paramName];
};

onMounted(() => {
  nextTick(() => {
    // 等待获取到localStorage中的sessionId再调用getAllTask
    const waitForSessionIdAndGetAllTask = () => {
      const checkSessionId = () => {
        const sessionId = localStorage.getItem("sessionId");
        if (sessionId) {
          getAllTask();
        } else {
          setTimeout(checkSessionId, 100);
        }
      };
      checkSessionId();
    };
    waitForSessionIdAndGetAllTask();
  });
  // 设置全局键盘事件监听
  setupGlobalKeyboardListener();
});
// 对外暴露方法
defineExpose({
  getAllTask,
  clearSelectedTask,
  resetSelectedParams,
  removeSelectedParam,
  autoSelectParam,
  selectedUnit,
  startDateTime,
  endDateTime,
  selectedParams, // 暴露selectedParams以便外部直接设置
});
onBeforeUnmount(() => {
  // 清理全局键盘事件监听
  cleanupGlobalKeyboardListener();
});

const handleSaveParams = () => {
  const paramsInfo: any = [];
  selectedParams.value.forEach((paramName) => {
    // 查找主参数或子参数
    let param: ParameterWithChildren | undefined;
    for (const p of props.parameters) {
      if (p.name === paramName) {
        param = p;
        break;
      }
      // 检查子参数
      if (p.children) {
        const child = p.children.find((c) => c.name === paramName);
        if (child) {
          param = child;
          break;
        }
      }
    }

    if (param) {
      paramsInfo.push({
        id: param.id,
        name: param.name,
        type: param.type,
      });
    }
  });
  const selectedTaskName = tasks.value.find(
    (task) => task.id.toString() === selectedTask.value
  )?.name;
  emit("save:save", {
    parameters: paramsInfo,
    showTask: true,
    taskName: selectedTaskName,
  });
};

const handleSaveTask = () => {
  // 发送保存任务事件到父组件
  let params: any = [];
  selectedParams.value.forEach((paramName) => {
    // 查找主参数或子参数
    let param: ParameterWithChildren | undefined;
    for (const p of props.parameters) {
      if (p.name === paramName) {
        param = p;
        break;
      }
      // 检查子参数
      if (p.children) {
        const child = p.children.find((c) => c.name === paramName);
        if (child) {
          param = child;
          break;
        }
      }
    }

    if (param) {
      params.push({
        id: param.id,
        name: param.name,
        type: param.type,
      });
    }
  });

  // 获取当前选中任务的名称
  const currentTask = tasks.value.find(
    (task) => task.id.toString() === selectedTask.value
  );
  const taskName = currentTask ? currentTask.name : "";
  emit("save:task", {
    parameters: params,
    showTask: true,
    taskName: taskName,
  });
};
const handleDeleteTask = () => {
  // 检查是否有选中的任务
  if (!selectedTask.value) {
    return;
  }
  emit("save:delete", {
    taskId: selectedTask.value,
    showTask: true,
  });
};

// 清空所有已选参数
const clearSelectedParams = () => {
  selectedParams.value = [];
  emit("update:selectedParameters", []);
  emit("update:selectedParametersInfo", []);
  selectedTask.value = "";
};

// 处理筛选确认
const handleFilterConfirm = () => {
  // 必须选择机组编号
  if (!selectedUnit.value) {
    emit("handleParameterError", "warning", "请选择机组编号");
    return;
  }
  // 开始时间结束时间必须选择
  if (!startDateTime.value && endDateTime.value) {
    emit("handleParameterError", "warning", "请选择开始时间");
    return;
  }
  if (!endDateTime.value && startDateTime.value) {
    emit("handleParameterError", "warning", "请选择结束时间");
    return;
  }
  if (
    startDateTime.value &&
    endDateTime.value &&
    startDateTime.value >= endDateTime.value
  ) {
    emit("handleParameterError", "warning", "开始时间必须小于结束时间");
    return;
  }
  // 可以在这里触发事件通知父组件
  let prevSelectedUnit = localStorage.getItem("unitCode");
  if (selectedUnit.value != prevSelectedUnit) {
    // 重新查询参数，清空绘图数据
    localStorage.setItem("unitCode", selectedUnit.value);
    localStorage.setItem("startTime", startDateTime.value);
    localStorage.setItem("endTime", endDateTime.value);
    emit("refresh:parameter");
  } else {
    // 只重新查询绘图数据
    localStorage.setItem("startTime", startDateTime.value);
    localStorage.setItem("endTime", endDateTime.value);
    emit("refresh:dataViewer");
  }
};
</script>

<style scoped>
@import "../../../src/assets/css/theme.css";
@import "../../../src/assets/css/buttons.css";
.parameter-selector {
  display: flex;
  flex-direction: column;
  gap: 10px;
  height: 100%;
  overflow: hidden;
}

/* 筛选区域样式 */
.filter-section {
  background: var(--sub-plate-bg-color);
  border-radius: 8px;
  border: 1px solid var(--modal-main-border-color);
  padding: 10px 8px;
}

.filter-row {
  display: flex;
  gap: 8px;
  align-items: center;
  flex-wrap: wrap;
}

.filter-item {
  display: flex;
  flex-direction: row;
  align-items: center;
  gap: 6px;
  flex: 0 0 auto;
}

.filter-item-button {
  margin-left: auto;
}

.filter-label {
  font-size: 13px;
  color: var(--text-color);
  font-weight: 500;
  white-space: nowrap;
  flex-shrink: 0;
}

.filter-select {
  width: 165px;
  padding: 4px 8px;
  font-size: 14px;
  border-radius: 4px;
  border: 1px solid var(--select-border-color);
  background: var(--select-background);
  color: var(--text-color);
}

.filter-date-input {
  width: 140px;
  padding: 4px 8px;
  font-size: 13px;
  border-radius: 4px;
  /*transition: all 0.2s ease;*/
  background: var(--input-background);
  border: 1px solid var(--input-border-color);
  color: var(--text-color);
}
.filter-datetime-input {
  width: 165px;
}

.confirm-filter-btn {
  min-width: 70px;
  height: 28px;
  padding: 6px 12px;
  font-size: 13px;
}

/* Tab样式 */
.tab-header {
  display: flex;
  border-bottom: 1px solid var(--modal-divide);
  background: var(--sub-plate-bg-color);
  padding: 0 2px;
}

.tab-button {
  padding: 8px 20px;
  background: none;
  border: none;
  border-bottom: 2px solid transparent;
  color: var(--text-color);
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.2s;
  position: relative;
  margin-bottom: -1px;
}

.tab-button:hover {
  color: var(--btn-hover-color);
  background: rgba(30, 64, 175, 0.05);
}

.tab-button.active {
  color: var(--title-color);
  border-bottom-color: var(--title-color);
  background: var(--sub-plate-bg-color);
}

.tab-content {
  display: flex;
  flex-direction: column;
  flex: 1;
  min-height: 0;
  overflow: hidden;
}

.empty-tab-content {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 200px;
  color: var(--preview-text-color);
  font-size: 14px;
}

.selector-card {
  background: var(--sub-plate-bg-color);
  /* background:red; */
  border-radius: 8px;
  border: 1px solid var(--modal-main-border-color);
  overflow: hidden;
  display: flex;
  flex-direction: column;
  position: relative;
}

.parameter-card {
  flex: 1;
  min-height: 0;
  display: flex;
  flex-direction: column;
}

.task-card {
  flex: 0 0 auto;
  height: 22%;
}

.card-header {
  padding: 12px 16px;
  border-bottom: 1px solid var(--modal-divide);
  background: var(--sub-plate-bg-color);
  flex-shrink: 0;
}

.card-title {
  font-size: 16px;
  font-weight: 600;
  margin: 0;
  color: var(--text-color);
}

.card-content {
  padding: 12px 16px;
  overflow-y: auto;
  flex: 1;
  min-height: 150px;
  background: var(--sub-plate-bg-color);
}

.parameter-group {
  display: flex;
  flex-direction: column;
}

.search-box {
  padding-top: 8px;
}

.tech-input {
  width: 76%;
  padding: 8px 12px;
  font-size: 15px;
  border-radius: 4px;
  /*transition: all 0.2s ease;*/
  background: var(--input-background);
  border: 1px solid var(--input-border-color);
  color: var(--text-color);
  box-shadow: inset 0 0 5px var(--input-shadow-color);
}

.tech-input:focus {
  border: 1px solid rgba(56, 189, 248, 0.5);
  box-shadow: var(--input-shadow-color);
}

.parameter-list {
  display: flex;
  flex-direction: column;
  /* gap: 8px; */
  max-height: 100%;
  overflow-y: auto;
}

/* 参数项容器 */
.parameter-item-container {
  display: flex;
  flex-direction: column;
  margin-bottom: 2px;
}

/* 修改参数项样式以支持展开/折叠 */
.parameter-item {
  padding: 4px 0;
  transition: background-color 0.2s;
  border-radius: 4px;
}

.parameter-item:hover {
  background-color: var(--btn-hover-color);
}

.parameter-item.has-children {
  cursor: pointer;
}

.parameter-item-content {
  display: flex;
  align-items: center;
  width: 100%;
}

/* 展开/折叠按钮 */
.expand-btn {
  background: none;
  border: none;
  width: 20px;
  height: 20px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  color: var(--text-color);
  padding: 0;
  margin-right: 4px;
  transition: transform 0.2s;
}

.expand-btn svg {
  transition: transform 0.2s;
}

.expand-btn svg.rotate-90 {
  transform: rotate(90deg);
}

/* 子参数样式 */
.parameter-children {
  margin-left: 20px;
  border-left: 1px dashed var(--border-color-base);
  padding-left: 10px;
  animation: slideDown 0.2s ease-out;
}

@keyframes slideDown {
  from {
    opacity: 0;
    transform: translateY(-10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.parameter-child-item {
  padding: 4px 0;
  margin-left: 5px;
  transition: background-color 0.2s;
  border-radius: 4px;
}

.parameter-child-item:hover {
  background-color: rgba(30, 64, 175, 0.05);
}

.tech-checkbox {
  display: flex;
  align-items: flex-start;
  gap: 10px;
  cursor: pointer;
  position: relative;
  width: 100%;
}

.tech-checkbox input {
  position: absolute;
  opacity: 0;
  cursor: pointer;
  height: 0;
  width: 0;
}

.param-checkbox {
  border: 1px solid var(--btn-click-color);
  background-color: var(--ant-checkbox-inner);
  color: var(--global-color-white);
  appearance: none;
  -webkit-appearance: none;
  width: 16px !important;
  height: 16px !important;
  border-radius: 4px; /* 圆角 */
  outline: none;
  cursor: pointer;
  position: relative;
  transition: all 0.2s ease; /* 平滑过渡效果 */
}
.param-checkbox:checked {
  color: var(--global-color-white);
  background-color: var(--ant-checkbox-checked);
  border-color: var(--btn-click-color);
}
.param-checkbox:checked::after {
  content: "";
  position: absolute;
  left: 30%;
  top: 1px;
  width: 6px;
  height: 10px;
  border-width: 0 2px 2px 0;
  transform: rotate(45deg);
}
.checkbox-custom {
  position: relative;
  height: 18px;
  width: 18px;
  min-width: 18px;
  border-radius: 4px;
  border: 1px solid var(--btn-click-color);
  background-color: var(--ant-checkbox-inner);
  color: var(--global-color-white);
}

.tech-checkbox input:checked ~ .checkbox-custom {
  color: var(--global-color-white);
  background-color: var(--ant-checkbox-checked);
  border-color: var(--btn-click-color);
}

.checkbox-custom:after {
  content: "";
  position: absolute;
  display: none;
  left: 6px;
  top: 2px;
  width: 5px;
  height: 10px;
  border-width: 0 2px 2px 0;
  transform: rotate(45deg);
}

.tech-checkbox input:checked ~ .checkbox-custom:after {
  display: block;
}

.checkbox-label {
  color: var(--text-color);
  word-break: break-word;
  word-wrap: break-word;
  overflow-wrap: break-word;
  hyphens: auto;
}

.task-controls {
  display: flex;
  flex-direction: column;
  gap: 10px;
  min-height: 100px;
}

.select-wrapper {
  position: relative;
}

.select-container {
  position: relative;
}

.clear-btn {
  position: absolute;
  right: 12px;
  top: 50%;
  transform: translateY(-50%);
  background: none;
  border: none;
  cursor: pointer;
  padding: 4px;
  color: var(--text-color);
}

.clear-btn:hover {
  color: var(--global-color-black);
}

.tech-select {
  display: block;
  width: 100%;
  padding: 8px 32px 8px 12px;
  font-size: 14px;
  border-radius: 4px;
  border: 1px solid var(--select-border-color);
  background: var(--select-background);
  color: var(--text-color);

  option.truncate-option {
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    max-width: 100%;
  }
  appearance: none;
  cursor: pointer;
  text-overflow: ellipsis;
  overflow: hidden;
  white-space: nowrap;
}

.tech-select option {
  padding: 8px 12px;
}

.tech-select[multiple],
.tech-select[size="4"] {
  max-height: 50px;
  overflow-y: auto;
}

.tech-select:focus {
  outline: none;
  border-color: rgba(30, 64, 175, 0.4);
  box-shadow: 0 0 0 2px rgba(59, 130, 246, 0.1);
}

.select-arrow {
  position: absolute;
  right: 12px;
  top: 40%;
  width: 10px;
  height: 10px;
  border-right: 2px solid var(--text-color);
  border-bottom: 2px solid var(--text-color);
  pointer-events: none;
  transform: translateY(-50%) rotate(45deg);
}

.tooltip-container {
  position: relative;
  display: inline-block;
}

.tooltip-text {
  visibility: hidden;
  width: auto;
  background-color: #333;
  color: #fff;
  text-align: center;
  border-radius: 4px;
  padding: 5px 8px;
  position: absolute;
  z-index: 1;
  bottom: 125%;
  left: 50%;
  transform: translateX(-50%);
  opacity: 0;
  transition: opacity 0.3s;
  font-size: 12px;
  white-space: nowrap;
}

.tooltip-text::after {
  content: "";
  position: absolute;
  top: 100%;
  left: 50%;
  margin-left: -5px;
  border-width: 5px;
  border-style: solid;
  border-color: #333 transparent transparent transparent;
}

.tooltip-container:hover .tooltip-text {
  visibility: visible;
  opacity: 1;
}

.tech-btn svg {
  flex-shrink: 0;
}

.save-btn {
  width: 100%;
  min-width: 60px;
}

.delete-btn {
  color: var(--error-color) !important;
  border: 1px solid var(--error-color) !important;
}

.delete-btn:hover {
  color: var(--text-color) !important;
  background: var(--error-color) !important;
}

/* Loading样式 - 只在card-content区域显示 */
.card-loading-overlay {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: var(--loading-bg-color);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.spinner {
  border: 5px solid #fcfcfc;
  border-top: 5px solid #3498db;
  border-radius: 50%;
  width: 40px;
  height: 40px;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}

/* 暗黑模式下的loading样式 */

.expand-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.clear-button {
  width: 38px;
  height: 38px;
}

/* 1024*768分辨率适配 */
@media (max-width: 1024px) {
  .parameter-selector {
    gap: 6px;
  }

  .filter-section {
    padding: 6px 8px;
  }

  .filter-row {
    gap: 8px;
  }

  .filter-item {
    min-width: 100px;
    gap: 6px;
  }

  .filter-label {
    font-size: 11px;
  }

  .filter-select {
    width: 100px;
    font-size: 11px;
    padding: 4px 6px;
  }

  .filter-datetime-input {
    width: 100px;
    font-size: 11px;
    padding: 4px 6px;
  }

  .confirm-filter-btn {
    min-width: 50px;
    height: 28px;
    font-size: 11px;
    padding: 4px 8px;
  }

  .tab-button {
    padding: 8px 12px;
    font-size: 12px;
  }

  .card-header {
    padding: 6px 10px;
  }

  .card-title {
    font-size: 12px;
  }

  .card-content {
    padding: 6px 10px;
    min-height: 120px;
  }

  .tech-input {
    padding: 4px 6px;
    font-size: 11px;
    width: 72%;
  }

  .parameter-item {
    padding: 2px 0;
  }

  .parameter-child-item {
    padding: 2px 0;
  }

  .tech-checkbox {
    gap: 6px;
  }

  .checkbox-label {
    font-size: 11px !important;
  }

  .tech-select {
    padding: 4px 20px 4px 6px;
    font-size: 11px;
  }

  .task-controls {
    display: flex;
    flex-direction: column;
    gap: 4px;
  }

  .task-controls .flex {
    justify-content: space-between;
    width: 100%;
  }

  .tech-btn {
    padding: 4px 8px !important;
    font-size: 11px;
    min-width: auto;
  }

  .tech-btn svg {
    width: 12px;
    height: 12px;
  }

  .tech-input {
    width: 76%;
    padding: 2px 4px;
    font-size: 11px;
  }

  .clear-button {
    width: 10px;
    height: 24px;
  }

  .tooltip-container {
    flex: 1;
  }

  .save-btn {
    width: 100%;
    min-width: auto;
    padding: 4px !important;
    justify-content: center;
  }

  .task-card {
    height: 150px;
  }

  /* 调整参数树视图的间距 */
  .parameter-list {
    gap: 4px;
  }
}

.tech-input::placeholder {
  color: var(--preview-text-color);
}
.warn-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.6);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1100;
  backdrop-filter: blur(3px);
}
.warn-title {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
  color: var(--text-color);
}
.modal-main {
  border: 1px solid var(--modal-main-border-color);
}
.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.warn-close {
  background: none;
  border: none;
  padding: 1px;
  cursor: pointer;
  color: var(--text-color);
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 4px;
}

.warn-close:hover {
  background-color: rgba(0, 0, 0, 0.05);
  color: var(--btn-click-color);
}
</style>
